package cz.data.gateway.admin.rest;

import cz.data.common.annotation.DataInner;
import cz.data.common.base.BaseResponse;
import cz.data.gateway.model.dto.GatewayRouteVo;
import cz.data.gateway.admin.mapstruct.GatewayRouteMapper;
import cz.data.gateway.admin.service.IGatewayRouteService;
import cz.data.gateway.model.dto.RouteDefinitionDto;
import cz.data.gateway.model.entity.GatewayRoute;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DataInnerController {

    @Autowired
    IGatewayRouteService gatewayRoutService;
    @Autowired
    GatewayRouteMapper gatewayRouteMapper;

    @DataInner
    @ApiOperation(value = "已发布网关路由列表")
    @GetMapping(value = "/api/admin/gateway/routes/release",
            consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE},
            produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE})
    public List<GatewayRouteVo> release() {
        List<GatewayRoute> routes = gatewayRoutService.releaseRouters();
        return routes.stream().map(gatewayRouteMapper::toVO).collect(Collectors.toList());
    }

    @DataInner
    @ApiOperation(value = "新增网关路由")
    @PostMapping(value = "/api/admin/gateway/inner/routes")
    public BaseResponse add(@Valid @RequestBody RouteDefinitionDto definition) {
        GatewayRoute gatewayRout = gatewayRouteMapper.toEntity(definition);
        return BaseResponse.withBoolean(gatewayRoutService.add(gatewayRout));
    }

    @DataInner
    @ApiOperation(value = "修改网关路由")
    @PutMapping(value = "/api/admin/gateway/inner/routes")
    public BaseResponse update(@Valid @RequestBody RouteDefinitionDto definition) {
        GatewayRoute gatewayRout = gatewayRouteMapper.toEntity(definition);
        return BaseResponse.withBoolean(gatewayRoutService.update(gatewayRout));
    }

    @DataInner
    @ApiOperation(value = "删除网关路由")
    @ApiImplicitParam(paramType = "path", name = "id", value = "网关路由ID", required = true, dataType = "string")
    @DeleteMapping(value = "/api/admin/gateway/inner/{id}")
    public BaseResponse delete(@PathVariable String id) {
        return BaseResponse.withBoolean(gatewayRoutService.delete(id));
    }
}
